<template>
  <inline-Modal
    :visible="visible"
    title="项目信息管理"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
    >
      确定
    </a-button>
    <div class="editorPage-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <div class="warp-container">
          <a-row>
            <a-col :span="16">
              <a-form-model-item
                label="项目名称"
                prop="proName"
                :rules="{
                  required: !isDisabled,
                  message: '请输入项目名称',
                }"
              >
                <a-input
                  v-model="form.proName"
                  :disabled="isDisabled"
                  :placeholder="isDisabled ? '' : '请输入'"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="项目简称">
                <a-input
                  v-model="form.proAbbreviation"
                  placeholder="请输入"
                ></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="项目编号">
                <a-input v-model="form.proCode" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目类型"
                prop="engType"
                :rules="{
                  required: !isDisabled,
                  message: '请选择项目类型',
                }"
              >
                <a-select
                  :disabled="isDisabled"
                  showSearch
                  allowClear
                  :placeholder="isDisabled ? '' : '请选择'"
                  :filter-option="filterOption"
                  v-model="form.engType"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in engTypeSource"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="省市县"
                prop="workArea"
                :rules="{
                  required: !isDisabled,
                  message: '请选择省市县',
                }"
              >
                <a-input
                  v-if="isDisabled"
                  :value="strReplace(parameter.workArea)"
                  disabled
                ></a-input>
                <a-cascader
                  v-else
                  placeholder="请选择"
                  :options="provinceSource"
                  :field-names="{
                    label: 'name',
                    value: 'name',
                    children: 'children',
                  }"
                  v-model="form.workArea"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-model-item
                label="项目状态"
                prop="proStatus"
                :rules="{
                  required: !isDisabled,
                  message: '请选择项目状态',
                }"
              >
                <a-select
                  :disabled="isDisabled"
                  showSearch
                  allowClear
                  :placeholder="isDisabled ? '' : '请选择'"
                  :filter-option="filterOption"
                  v-model="form.proStatus"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in proStatusSource"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目等级"
                prop="projectLevel"
                :rules="{
                  required: !isDisabled,
                  message: '请选择项目等级',
                }"
              >
                <a-select
                  :disabled="isDisabled"
                  showSearch
                  allowClear
                  :placeholder="isDisabled ? '' : '请选择'"
                  :filter-option="filterOption"
                  v-model="form.projectLevel"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in proLevelSource"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目规模"
                prop="constructionScale"
                :rules="{
                  required: !isDisabled,
                  message: '请输入项目规模',
                }"
              >
                <a-input
                  :disabled="isDisabled"
                  :placeholder="isDisabled ? '' : '请输入'"
                  v-model="form.constructionScale"
                ></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                label="计划开工时间"
                prop="startDate"
                :rules="{
                  required: !isDisabled,
                  message: '请选择计划开工时间',
                }"
              >
                <a-date-picker
                  :disabled="isDisabled"
                  style="width: 100%"
                  v-model="form.startDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="isDisabled ? '' : '请选择'"
                  :disabled-date="disabledStartDate"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                label="计划竣工时间"
                prop="endDate"
                :rules="{
                  required: !isDisabled,
                  message: '请选择计划竣工时间',
                }"
              >
                <a-date-picker
                  :disabled="isDisabled"
                  style="width: 100%"
                  v-model="form.endDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="isDisabled ? '' : '请选择'"
                  :disabled-date="disabledEndDate"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                label="实际开工时间"
                prop="realityStartDate"
                :rules="{
                  required: !isDisabled,
                  message: '请选择实际开工时间',
                }"
              >
                <a-date-picker
                  :disabled="isDisabled"
                  style="width: 100%"
                  v-model="form.realityStartDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="isDisabled ? '' : '请选择'"
                  :disabled-date="disabledStartRealityDate"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                label="实际竣工时间"
                prop="realityEndDate"
                :rules="{
                  required: false,
                  message: '请选择实际竣工时间',
                }"
              >
                <a-date-picker
                  :disabled="isDisabled"
                  style="width: 100%"
                  v-model="form.realityEndDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="isDisabled ? '' : '请选择'"
                  :disabled-date="disabledEndRealityDate"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-model-item
                label="总投资额"
                class="input-unit"
                prop="roadMoney"
                :rules="[
                  {
                    required: !isDisabled,
                    message: '请输入总投资额',
                  },
                  {
                    pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,6})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                    message: '请输入正确的投资金额，可保留六位小数',
                  },
                ]"
              >
                <a-input
                  :disabled="isDisabled"
                  v-model="form.roadMoney"
                  :placeholder="isDisabled ? '' : '请输入'"
                  :maxLength="14"
                />
                <div class="unit">万元</div>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="项目经理"
                prop="contacts"
                :rules="{
                  required: !isDisabled,
                  message: '请输入项目经理',
                }"
              >
                <a-input
                  :disabled="isDisabled"
                  v-model="form.contacts"
                  :placeholder="isDisabled ? '' : '请输入'"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="联系方式"
                prop="contactsPhone"
                :rules="{
                  required: !isDisabled,
                  message: '请输入联系方式',
                }"
              >
                <a-input
                  :disabled="isDisabled"
                  v-model="form.contactsPhone"
                  :placeholder="isDisabled ? '' : '请输入'"
                ></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item
            label="项目地址"
            prop="address"
            :rules="{
              required: !isDisabled,
              message: '请输入项目地址',
            }"
          >
            <a-input
              v-model="form.address"
              :disabled="isDisabled"
              :placeholder="isDisabled ? '' : '请输入'"
            ></a-input>
          </a-form-model-item>
          <a-form-model-item
            label="项目简介"
            prop="introduction"
            :rules="{
              required: true,
              message: '请输入项目简介',
            }"
          >
            <a-textarea
              :rows="4"
              v-model="form.introduction"
              placeholder="请输入"
            />
          </a-form-model-item>
          <a-form-model-item
            label="项目封面"
            prop="proImage"
            :rules="{
              required: false,
              message: '请上传项目封面',
            }"
          >
            <UploadImg
              :record="upLoadImgData"
              :config="upLoadImgConfigData"
              v-model="form.proImage"
              @change="
                (e) => {
                  upLoadImage(e, 'proImage');
                }
              "
            />
          </a-form-model-item>
          <a-form-model-item
            label="效果图"
            prop="effectImages"
            :rules="{
              required: false,
              message: '请上传效果图',
            }"
          >
            <UploadImg
              :record="effectData"
              :config="upLoadImgConfigData"
              v-model="form.effectImages"
              @change="
                (e) => {
                  upLoadImage(e, 'effectImages');
                }
              "
            />
          </a-form-model-item>
          <a-form-model-item
            label="全景图"
            prop="panoramaImages"
            :rules="{
              required: false,
              message: '请上传全景图',
            }"
          >
            <UploadImg
              :record="upLoadImgData"
              :config="upLoadImgConfigData"
              v-model="form.panoramaImages"
              @change="
                (e) => {
                  upLoadImage(e, 'panoramaImages');
                }
              "
            />
          </a-form-model-item>
          <a-form-model-item
            label="宣传视频"
            prop="promotionalVideo"
            :rules="{
              required: false,
              message: '请上传宣传视频',
            }"
          >
            <bjUploadVideo
              :count="1"
              v-model="form.promotionalVideo"
              @change="upLoadFile($event, 'promotionalVideo')"
              :replaceFields="{
                fileName: 'name',
                videoSrc: 'url',
              }"
            ></bjUploadVideo>
          </a-form-model-item>
        </div>
        <a-divider />
        <div class="sub-title">
          参建单位信息
        </div>
        <div class="table-container">
          <vxe-table
            ref="xTable"
            align="left"
            show-overflow
            show-header-overflow
            border="default"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="loading"
          >
            <vxe-column
              type="seq"
              width="80"
              title="序号"
              align="center"
            ></vxe-column>
            <vxe-column field="orgName" title="单位名称"> </vxe-column>
            <vxe-column field="orgTypeDesc" title="单位类型"> </vxe-column>
            <vxe-column field="orgPerson" title="联系人"> </vxe-column>
            <vxe-column field="orgTelephone" title="联系方式"> </vxe-column>
          </vxe-table>
        </div>
      </a-form-model>
    </div>
  </inline-Modal>
</template>

<script>
import moment from "moment";
import { axios } from "@/utils/request";
//上传图片
import UploadImg from "@/components/TopVUI/k-form-design/packages/UploadImg";
//视频上传
import bjUploadVideo from "@/components/extendCustom/bj-upload-video";
import areaData from "@/components/_utils/area-json.js";
import { getDicItemByCode } from "@/api/common.js";
export default {
  components: {
    UploadImg,
    bjUploadVideo,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      effectData: {
        //上传图片数据
        options: {
          uploadWay: "minio",
          width: "100%", //宽度
          drag: false, //是否可拖拽
          fileName: "file", //文件参数名
          multiple: false, //是否支持多选
          limit: 20, //上传最大数量
          disabled: false, //是否禁用
          data: "{}", //额外参数（json格式）
          listType: "picture-card", //上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
          action: "/document/minio/uploadfile", //上传请求地址
          headers: {}, //请求头部
          downloadWay: "a", //下载方式  可选a、ajax
          dynamicFun: "", //动态函数名
          placeholder: "上传", //上传区文字提示
          defaultValue: [], //默认值
        },
      },
      upLoadImgData: {
        //上传图片数据
        options: {
          uploadWay: "minio",
          width: "100%", //宽度
          drag: false, //是否可拖拽
          fileName: "file", //文件参数名
          multiple: false, //是否支持多选
          limit: 1, //上传最大数量
          disabled: false, //是否禁用
          data: "{}", //额外参数（json格式）
          listType: "picture-card", //上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
          action: "/document/minio/uploadfile", //上传请求地址
          headers: {}, //请求头部
          downloadWay: "a", //下载方式  可选a、ajax
          dynamicFun: "", //动态函数名
          placeholder: "上传", //上传区文字提示
          defaultValue: [], //默认值
        },
      },
      upLoadImgConfigData: {}, //上传图片数据
      submitLoading: false,
      form: {
        uuid: "",
        //项目名称
        proName: "",
        //项目简称
        proAbbreviation: "",
        //项目编号
        proCode: "",
        //项目类型
        engType: undefined,
        //省市县
        workArea: [],
        //项目状态
        proStatus: undefined,
        //项目等级
        projectLevel: undefined,
        //项目规模
        constructionScale: "",
        //计划开工时间
        startDate: "",
        //计划竣工时间
        endDate: "",
        //实际开工时间
        realityStartDate: "",
        //实际竣工时间
        realityEndDate: "",
        //总投资额
        roadMoney: "",
        //项目经理
        contacts: "",
        //联系方式
        contactsPhone: "",
        //项目地址
        address: "",
        //项目简介
        introduction: "",
        //封面
        proImage: [],
        //效果图
        effectImages: [],
        //全景图
        panoramaImages: [],
        //宣传视频
        promotionalVideo: [],
      },
      rules: {},
      tableData: [],
      loading: false,
      //项目类型
      engTypeSource: [],
      //省市区
      provinceSource: areaData,
      //项目状态
      proStatusSource: [],
      //项目等级
      proLevelSource: [],
      //
      isDisabled: true,
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getData() {
      this.getEngTypeData();
      this.getProStatusData();
      this.getProLevelData();
      this.getDetail();
    },

    //查询工程类型
    getEngTypeData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "engineeringType" })
          .then((res) => {
            let { data } = res;
            this.engTypeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.engTypeSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询项目状态
    getProStatusData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "proStatus" })
          .then((res) => {
            let { data } = res;
            this.proStatusSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.proStatusSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询项目等级
    getProLevelData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "proLevel" })
          .then((res) => {
            let { data } = res;
            this.proLevelSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.proLevelSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    getDetail() {
      let { parameter } = this;
      let { proId } = parameter;
      if (!proId) {
        this.isDisabled = false;
      } else {
        this.isDisabled = true;
      }
      this.form = {
        uuid: parameter.uuid,
        //项目名称
        proName: parameter?.proName ?? "",
        //项目简称
        proAbbreviation: parameter?.proAbbreviation ?? "",
        //项目编号
        proCode: parameter?.proCode ?? "",
        //项目类型
        engType: parameter?.engType ?? undefined,
        //省市县
        workArea: parameter?.workArea ? parameter?.workArea.split("@") : [],
        //项目状态
        proStatus: parameter?.proStatus ?? undefined,
        //项目等级
        projectLevel: parameter?.projectLevel ?? undefined,
        //项目规模
        constructionScale: parameter?.constructionScale ?? "",
        //计划开工时间
        startDate: parameter?.startDate ?? "",
        //计划竣工时间
        endDate: parameter?.endDate ?? "",
        //实际开工时间
        realityStartDate: parameter?.realityStartDate ?? "",
        //实际竣工时间
        realityEndDate: parameter?.realityEndDate ?? "",
        //总投资额
        roadMoney: parameter?.roadMoney ?? "",
        //项目经理
        contacts: parameter?.contacts ?? "",
        //联系方式
        contactsPhone: parameter?.contactsPhone ?? "",
        //项目地址
        address: parameter?.address ?? "",
        //项目简介
        introduction: parameter.introduction,
        //封面
        proImage: JSON.parse(parameter?.proImage ?? "[]"),
        //效果图
        effectImages: JSON.parse(parameter?.effectImages ?? "[]"),
        //全景图
        panoramaImages: JSON.parse(parameter?.panoramaImages ?? "[]"),
        //宣传视频
        promotionalVideo: JSON.parse(parameter?.promotionalVideo ?? "[]"),
      };
      this.tableData = parameter?.unitList ?? [];
    },

    //判断维结束时间大于完工时间
    disabledStartDate(current) {
      if (this.form.startDate == null && this.form.endDate == null) {
        return;
      }
      return current >= moment(this.form.endDate).endOf("day");
    },

    disabledEndDate(current) {
      if (this.form.startDate == null && this.form.endDate == null) {
        return;
      }
      return current <= moment(this.form.startDate).endOf("day");
    },

    disabledStartRealityDate(current) {
      if (
        this.form.realityStartDate == null &&
        this.form.realityEndDate == null
      ) {
        return;
      }
      return current >= moment(this.form.realityEndDate).endOf("day");
    },

    disabledEndRealityDate(current) {
      if (
        this.form.realityStartDate == null &&
        this.form.realityEndDate == null
      ) {
        return;
      }
      return current <= moment(this.form.realityStartDate).endOf("day");
    },
    handelOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form, parameter } = this;
          const videoList = form.promotionalVideo.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          let formJson = {};
          if (!parameter.proId) {
            formJson = {
              uuid: form.uuid,
              //项目名称
              proName: form.proName,
              //项目简称
              proAbbreviation: form.proAbbreviation,
              //项目编号
              proCode: form.proCode,
              //项目类型
              engType: form.engType,
              //省市县
              workArea: form.workArea.join("@"),
              //项目状态
              proStatus: form.proStatus,
              //项目等级
              projectLevel: form.projectLevel,
              //项目规模
              constructionScale: form.constructionScale,
              //计划开工时间
              startDate: form.startDate,
              //计划竣工时间
              endDate: form.endDate,
              //实际开工时间
              realityStartDate: form.realityStartDate,
              //实际竣工时间
              realityEndDate: form.realityEndDate,
              //总投资额
              roadMoney: form.roadMoney,
              //项目经理
              contacts: form.contacts,
              //联系方式
              contactsPhone: form.contactsPhone,
              //项目地址
              address: form.address,
              //项目简介
              introduction: form.introduction,
              //封面
              proImage: JSON.stringify(form.proImage),
              //效果图
              effectImages: JSON.stringify(form.effectImages),
              //全景图
              panoramaImages: JSON.stringify(form.panoramaImages),
              //宣传视频
              promotionalVideo: JSON.stringify(videoList),
            };
          } else {
            formJson = {
              uuid: form.uuid,
              //项目简称
              proAbbreviation: form.proAbbreviation,
              //项目简介
              introduction: form.introduction,
              //封面
              proImage: JSON.stringify(form.proImage),
              //效果图
              effectImages: JSON.stringify(form.effectImages),
              //全景图
              panoramaImages: JSON.stringify(form.panoramaImages),
              //宣传视频
              promotionalVideo: JSON.stringify(videoList),
            };
          }
          this.submitLoading = true;
          axios
            .post(`/mdata/sysProject/updateProject`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },
    handelCancel() {
      this.$emit("update:visible", false);
      this.$parent.getData();
    },
    //上传图片
    upLoadImage(files, domain) {
      this.form[domain] = files;
    },
    //上传视频
    upLoadFile({ file, index }, domain) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[domain][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form[domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[domain][index], "loading", false);
        });
    },
    strReplace(str) {
      if (str) {
        return str.replace(/@/g, ">");
      } else {
        return "";
      }
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 130px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .editorPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-bottom: 20px;
    .input-unit {
      .unit {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 14px;
        color: #8a8a8c;
      }
      /deep/.ant-input {
        padding-right: 40px;
      }
    }
    .sub-title {
      font-size: 18px;
      color: #333333;
      margin-bottom: 16px;
    }
    .warp-container {
      padding-right: 110px;
      box-sizing: border-box;
      /deep/.bj-upload-file {
        .choosed-file-warp {
          width: 100%;
          .file-list {
            .base-info {
              background: rgba(24, 144, 255, 0.1);
            }
          }
        }
      }
    }
    .table-container {
      margin-bottom: 20px;
    }
  }
}
</style>
